package classpath

import (
	"errors"
	"strings"
)

// 组合多个查找方式
type CompositeEntry []Entry

// 允许同时从多个Entry下寻找
func newCompositeEntry(pathList string) CompositeEntry {
	var compositeEntry []Entry
	for _, path := range strings.Split(pathList, pathListSeparator) {
		// 实际创建节点
		entry := newEntry(path)
		compositeEntry = append(compositeEntry, entry)
	}
	return compositeEntry
}

// 从各个Entry中查找目标class文件的字节流
func (self CompositeEntry) ReadClass(classname string) ([]byte, Entry, error) {
	// 遍历内部的各个Entry
	for _, entry := range self {
		data, from, err := entry.ReadClass(classname)
		// 如果某个Entry找到了目标类，则返回
		if err == nil {
			return data, from, nil
		}
	}
	// 都没找到，抛出一个异常
	return nil, nil, errors.New("class not found " + classname)
}

// 返回此CompositeEntry的字符串表示
func (self CompositeEntry) String() string {
	strs := make([]string, len(self))
	for i, entry := range self {
		strs[i] = entry.String()
	}
	return strings.Join(strs, pathListSeparator)
}
